#!/user/bin/python
#-*- coding:utf-8 -*-

# import requests
# from  urllib import request
import json
import random
import threading
import time
# import requests
import urllib.request


def one_test(mac_t):
    mac_add = "20:82:C0:66:77:{:0>2X}".format(mac_t)
    payload = {
    "deviceStandard":222555,
    "deviceName":"newDevice30",
    "deviceZone":"qujiang",
    "deviceStatus":1,
    "deviceSellingStatus":0,
    "deviceLongitude":"108.93",
    "deviceLatitude":"34.27",
    "deviceEnvironmentSituation":"4度/25ml",
    "deviceDeviceSituation":"常温",
    "deviceMonitorAddress":"10.0.1.1",
    "deviceAddress":"西安市雁塔区",
    "deviceMacAddress":mac_add,
    "deviceCurrentIp":"192.168.1.1",
    "deviceChannelQuantity":20,
    "deviceChannelDistribute":"8,8,8,8",
    "devicePaymentType":3,
    "deviceIsdel":0,
    "deviceCertification":1
    }
    params = json.dumps(payload).encode('utf8')  
    #test_data_url_encode = urllib.parse.urlencode(test_data)
    AddVending_url = "http://cert.ccpbox.com/api/Vending/AddVending"
    head = {'Content-Type':'application/json',
                'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36",
                'Connection': 'keep-alive'
    }

    addvending_state = True
    while addvending_state:
        req = urllib.request.Request(AddVending_url, data=params,headers=head)
        response = urllib.request.urlopen(req)
        ret = response.read().decode('utf8')
        dict_ret = json.loads(ret)
        #print(dict_ret)
        addvending_state = dict_ret["success"]
        if addvending_state is True:
            #print("{:0>2X}".format(mac_t),end = ' ')
            #print(dict_ret)
            #print()
            deviceID = dict_ret["data"]

            break
        else:
            #print(dict_ret)
            print("{:0>2X}".format(mac_t),end = ' ')
            time.sleep(random.uniform(1,10))

    payload_ListenDevice = {"deviceId":deviceID,"macAddress":mac_add}
    deviceID_url = "http://cert.ccpbox.com/api/Vending/ListenDevice"

    while True:
        req1 = urllib.request.Request(deviceID_url, data=json.dumps(payload_ListenDevice).encode('utf8'),headers=head)
        response = urllib.request.urlopen(req1)
        print(payload["deviceName"])
        print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
        ret1 = response.read().decode('utf8')
        dict_ret1 = json.loads(ret1)
        state = dict_ret1["success"]
        if state is False:
            print(deviceID,end='\t')
            print(state)
        time.sleep(10)

#one_test(0x06)

x = 1
while x <= 100:
    threading.Thread(target=one_test, name='LoopThread',args=(x,)).start()
    x += 1
    print(x)
    #time.sleep(1)


# while True:
#     time.sleep(100)
#one_test(1)
